package com.fuli.app.controller;

import com.alibaba.fastjson.JSONObject;
import com.fuli.app.common.ActionResult;
import com.fuli.app.common.WxConfig;
import com.fuli.app.dto.UserDTO;
import com.fuli.app.entity.User;
import com.fuli.app.service.UserService;
import com.fuli.app.util.MD5Utils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.weixin4j.WeixinException;
import org.weixin4j.http.HttpsClient;
import org.weixin4j.http.Response;

import javax.servlet.http.HttpServletRequest;
import java.net.InetAddress;
import java.net.UnknownHostException;
@Api(tags = "登录接口")
@Controller
public class LoginController {
    @Autowired
    private UserService userService;

    @PostMapping("/login")
    public String login(@RequestParam String account, @RequestParam String password, HttpServletRequest request, Model model) {
        password = MD5Utils.encryptMD5(password);
        UsernamePasswordToken token = new UsernamePasswordToken(account, password);
        Subject currentUser = SecurityUtils.getSubject();
        currentUser.login(token);
        String ip = getIpAddress(request);
        User user = (User) SecurityUtils.getSubject().getSession().getAttribute("user");
        try {
            if (user != null)
                userService.updateLoginInfo(user.getId(), ip);
            if (user.getRole().equals("管理员")) {
                return "redirect:/index";
            } else {
                SecurityUtils.getSubject().logout();
                model.addAttribute("message", "用户角色未定义!");
                return "redirect:/login";
            }
        } catch (AuthenticationException e) {
            System.out.println(e.getMessage());
            model.addAttribute("message", e.getMessage());
            return "login";
        }
    }

    @GetMapping("/login")
    public String login() {
        return "login";
    }

    @GetMapping("/logout")
    public String logout() {
        SecurityUtils.getSubject().logout();
        return "redirect:/login";
    }

    private static String getIpAddress(HttpServletRequest request) {

        String ipAddress = request.getHeader("x-forwarded-for");

        if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
            ipAddress = request.getHeader("Proxy-Client-IP");
        }
        if (ipAddress == null || ipAddress.length() == 0 || "unknow".equalsIgnoreCase(ipAddress)) {
            ipAddress = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
            ipAddress = request.getRemoteAddr();

            if (ipAddress.equals("127.0.0.1") || ipAddress.equals("0:0:0:0:0:0:0:1")) {
                //根据网卡获取本机配置的IP地址
                InetAddress inetAddress = null;
                try {
                    inetAddress = InetAddress.getLocalHost();
                } catch (UnknownHostException e) {
                    e.printStackTrace();
                }
                ipAddress = inetAddress.getHostAddress();
            }
        }

        //对于通过多个代理的情况，第一个IP为客户端真实的IP地址，多个IP按照','分割
        if (null != ipAddress && ipAddress.length() > 15) {
            //"***.***.***.***".length() = 15
            if (ipAddress.indexOf(",") > 0) {
                ipAddress = ipAddress.substring(0, ipAddress.indexOf(","));
            }
        }

        return ipAddress;
    }
    @ApiOperation("验证微信用户是否有观看权限")
    @GetMapping("/getByOpenId/{openId}")
    public ActionResult<UserDTO> getByOpenId(@ApiParam("微信唯一标识") @PathVariable String openId){
        return userService.getByOpenId(openId);
    }

    @ApiOperation("获取openId接口")
    @GetMapping("/openId")
    @ResponseBody
    public ActionResult<String> openId(@ApiParam ("获取openId") @RequestParam String code) throws WeixinException {
        String openid = "";
        //拼接参数
        String param = "?grant_type=" + WxConfig.grant_type + "&appid=" + WxConfig.appid + "&secret=" + WxConfig.secret + "&js_code=" + code;

        //创建请求对象
        HttpsClient http = new HttpsClient();
        //调用获取access_token接口
        Response res = http.get("https://api.weixin.qq.com/sns/jscode2session" + param);
        //根据请求结果判定，是否验证成功
        JSONObject jsonObj = res.asJSONObject();
        if (jsonObj != null) {
            Object errcode = jsonObj.get("errcode");
            if (errcode != null) {
                return new ActionResult<>(0, "获取失败");
            }
            openid = jsonObj.getString("openid");
        }
        return new ActionResult<>(openid);
    }
}
